# coding = utf-8
# Author: 柚一
import datetime
import logging
import os.path

import allure
import jsonpath
import pytest

from core.globalContext import g_context
from extend.keywords import Keywords
from parse.ExcelCaseParser import load_context_from_excel

kewords = Keywords()

context = g_context()


@pytest.fixture(scope="session")
@allure.title("登陆进入指定租户")
def get_authorization():
    global token_res
    with allure.step("读取当前context.xlsx文件里的环境变量"):
        load_context_from_excel(r'D:\API\examples\excel_testcase')
        BASE_URL = context.get_dict("base_url")
    with allure.step("登陆的接口数据准备"):
        url = BASE_URL + '/elabnote/system/api/banmayu/users/login'
        data = {
            "username": "zxiaomei@zfish.company",
            "password": "xm123456!",
        }
    with allure.step("发送登录请求"):
        requests_data = {"url": url, "json": data}
        res = kewords.request_post(**requests_data)
        print('登陆返回的结果', res.json())
    with allure.step("获取返回结果里的accessToken保存为环境变量"):
        kewords.ex_jsonData(EXVALUE='$..accessToken', INDEX=0, VARNAME="accessToken")
    with allure.step("加入租户的接口数据准备"):
        tenant_id = context.get_dict("tenant_id")
        url = BASE_URL + '/elabnote/system/api/banmayu/tenant/' + tenant_id
        headers = {
            "authorization": context.get_dict("accessToken"),
        }
    with allure.step("发送加入指定租户请求"):
        requests_data = {"url": url, "headers": headers}
        res = kewords.request_patch(**requests_data)
        print('加入租户返回的结果', res.json())
    with allure.step("获取返回结果里的authorization保存为环境变量"):
        kewords.ex_jsonData(EXVALUE='$..accessToken', INDEX=0, VARNAME="authorization")

# 日志记录
# @pytest.hookimpl(hookwrapper=True, tryfirst=True)
# def pytest_runtest_makereport(item, call):
#     out = yield
#     res = out.get_result()
#     if res.when == "call":
#         logging.info(f"用例ID:{res.nodeid}")
#         logging.info(f"用例结果:{res.outcome}")
#         logging.info(f"故障表示:{res.longrepr}")
#         logging.info(f"异常:{call.excinfo}")
#         logging.info(f"用例耗时:{res.duration}")
#         logging.info("=====================================")


# LOG_PATH = './log'
#
#
# def pytest_configure(config):
#     now = datetime.datetime.now()  # 打印当前时间
#     data_str = now.strftime("%Y-%m-%d_%H-%M-%S")  # 2025-xx-xx-xx-xx-xx
#     # 文件名：每次都是最新的时间最新的文件  pytest_2025-xx-xx-xx-xx-xx.log
#     log_file_name = f'pytest_{data_str}.log'
#     # 文件路径放在哪 文件夹里面 文件夹
#     full_log_path = os.path.join(LOG_PATH, log_file_name)
#     config.option.log_file = full_log_path  # 将路径配置到pytest的log_file的录下
#     config.option.log_file_mode = 'a'  # 设置日志文件追加模式


if __name__ == '__main__':
    get_authorization()
